package org.yray.tts.media;

import org.yray.tts.format.WavFile;
import org.yray.tts.format.WavHeader;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class MediaStore711 implements IMediaStore{

    public Map<String,MediaByte> bsMap=new HashMap<>();

    private static int FORMAT=711;


    @Override
    public MediaByte toByte(String text) {
        MediaByte result=bsMap.get(text);
        if(result==null)
        {
           byte[] bs= MediaReadFile.readBytes(text,FORMAT);
           if(bs==null)
           {
               bs= MediaReadTss.readBytes(text,FORMAT);
               bs=G711Grabber.wavBody2G711Body(bs);
               WavFile wav711=new WavFile(MediaReadFile.filePath+ File.separator+FORMAT+File.separator+text+"_"+FORMAT+".wav", WavHeader.HEADER_711);
               wav711.write(bs);
               wav711.writeFileLen(bs.length);
               wav711.close();
           }
           //去掉头部
            bs=cutHeader(bs);
            result=byte2MediaByte(bs);
            bsMap.put(text,result);
        }
        return result;
    }

    private byte[] cutHeader(byte[] full)
    {
        byte[] body=new byte[full.length-80];
        System.arraycopy(full,80,body,0,body.length);
        return body;
    }
    public MediaByte byte2MediaByte(byte[] bs)
    {
        MediaByte mediaByte=new MediaByte();
        mediaByte.setBytes(bs);
        int begin=-1;
        int end=-1;
        for(int i=0;i<bs.length/2;i++)
        {
            if(begin==-1&&bs[i]!=-43)
            {
                begin=i;
            }
            if(end==-1&&bs[bs.length-i-1]!=-43)
            {
                end=bs.length-i-1;
            }
            if(begin!=-1&&end!=-1)
            {
                break;
            }
        }
        mediaByte.setBegin(begin>>1<<1);
        mediaByte.setEnd(end>>1<<1);
        return mediaByte;
    }
}
